package com.mspbots.teams.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class RabbitConfiguration {

    @Autowired
    private AmqpAdmin amqpAdmin;


    @Bean
    public void declareQueue() {
        Exchange exchange = ExchangeBuilder.fanoutExchange("msp.message.teams").build();
        this.amqpAdmin.declareExchange(exchange);

// 4 hours
        Queue queue = QueueBuilder.durable("teams.message.send").withArgument("x-message-ttl", 4 * 60 * 60 * 1000).build();
        this.amqpAdmin.declareQueue(queue);
        this.amqpAdmin.declareBinding(BindingBuilder.bind(queue)
                .to(exchange).with("teams.message.send").noargs());
// 4 hours
        Queue queueForward = QueueBuilder.durable("teams.message.sendForward").withArgument("x-message-ttl", 4 * 60 * 60 * 1000).build();
        this.amqpAdmin.declareQueue(queueForward);
        this.amqpAdmin.declareBinding(BindingBuilder.bind(queueForward)
                .to(exchange).with("teams.message.sendForward").noargs());

        Exchange logExchange = ExchangeBuilder.fanoutExchange("msp.message.teams.log").build();
        this.amqpAdmin.declareExchange(logExchange);

        Queue logQueue = QueueBuilder.durable("teams.message.send.log").build();
        this.amqpAdmin.declareQueue(logQueue);
        this.amqpAdmin.declareBinding(BindingBuilder.bind(logQueue)
                .to(logExchange).with("teams.message.send.log").noargs());


    }

    @Bean
    public void declareTeamsSync() {
        Exchange exchange = ExchangeBuilder.fanoutExchange("msp.teams.sync").build();
        this.amqpAdmin.declareExchange(exchange);

        Queue queueTeamsUsers = new Queue("teams.users");
        this.amqpAdmin.declareQueue(queueTeamsUsers);
        this.amqpAdmin.declareBinding(BindingBuilder.bind(queueTeamsUsers)
                .to(exchange).with("teams-sync-users").noargs());

    }


    @Bean
    public MessageConverter rabbitMessageConverter(ObjectMapper objectMapper) {
        return new Jackson2JsonMessageConverter(objectMapper);
    }
}
